#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pandas as pd
import openpyxl
from docx import Document
import json
import os

def read_excel_file(file_path, sheet_name=None):
    """读取Excel文件"""
    print(f"\n=== 读取文件: {file_path} ===")
    
    try:
        # 使用openpyxl读取Excel文件
        workbook = openpyxl.load_workbook(file_path, data_only=True)
        print(f"工作表列表: {workbook.sheetnames}")
        
        result = {}
        
        for sheet_name in workbook.sheetnames:
            print(f"\n--- 工作表: {sheet_name} ---")
            sheet = workbook[sheet_name]
            
            # 获取数据范围
            max_row = sheet.max_row
            max_col = sheet.max_column
            print(f"数据范围: {max_row}行 x {max_col}列")
            
            # 读取表头
            headers = []
            for col in range(1, max_col + 1):
                cell_value = sheet.cell(row=1, column=col).value
                headers.append(str(cell_value) if cell_value is not None else f"列{col}")
            
            print(f"表头: {headers}")
            
            # 读取前10行数据作为示例
            data = []
            for row in range(1, min(11, max_row + 1)):
                row_data = []
                for col in range(1, max_col + 1):
                    cell_value = sheet.cell(row=row, column=col).value
                    row_data.append(str(cell_value) if cell_value is not None else "")
                data.append(row_data)
            
            result[sheet_name] = {
                'headers': headers,
                'data': data,
                'max_row': max_row,
                'max_col': max_col
            }
            
            # 打印前几行数据
            print("前10行数据:")
            for i, row in enumerate(data[:10]):
                print(f"  行{i+1}: {row}")
        
        return result
        
    except Exception as e:
        print(f"读取Excel文件失败: {e}")
        return None

def read_word_file(file_path):
    """读取Word文件"""
    print(f"\n=== 读取文件: {file_path} ===")
    
    try:
        doc = Document(file_path)
        
        result = {
            'paragraphs': [],
            'tables': []
        }
        
        # 读取段落
        print("段落内容:")
        for i, paragraph in enumerate(doc.paragraphs[:20]):  # 只读取前20个段落
            text = paragraph.text.strip()
            if text:
                result['paragraphs'].append(text)
                print(f"  段落{i+1}: {text}")
        
        # 读取表格
        print(f"\n表格数量: {len(doc.tables)}")
        for i, table in enumerate(doc.tables):
            print(f"\n--- 表格 {i+1} ---")
            table_data = []
            
            for row_idx, row in enumerate(table.rows):
                row_data = []
                for cell in row.cells:
                    cell_text = cell.text.strip()
                    row_data.append(cell_text)
                table_data.append(row_data)
                
                # 只打印前10行
                if row_idx < 10:
                    print(f"  行{row_idx+1}: {row_data}")
            
            result['tables'].append({
                'table_index': i,
                'rows': len(table.rows),
                'cols': len(table.rows[0].cells) if table.rows else 0,
                'data': table_data
            })
        
        return result
        
    except Exception as e:
        print(f"读取Word文件失败: {e}")
        return None

def main():
    # 文件路径
    files = [
        "启动方案设备导入模板.xlsx",
        "附件1：程序化启动方案术语库（含三个子表）20250907（项目校核版）.xlsx",
        "附件2.110kV宝嘉变电站及110kV莲宝线1S1启动方案（例子）.docx"
    ]
    
    all_results = {}
    
    for file_name in files:
        if os.path.exists(file_name):
            if file_name.endswith('.xlsx'):
                result = read_excel_file(file_name)
            elif file_name.endswith('.docx'):
                result = read_word_file(file_name)
            
            if result:
                all_results[file_name] = result
        else:
            print(f"文件不存在: {file_name}")
    
    # 保存结果到JSON文件
    with open('file_analysis_result.json', 'w', encoding='utf-8') as f:
        json.dump(all_results, f, ensure_ascii=False, indent=2)
    
    print(f"\n=== 分析完成，结果已保存到 file_analysis_result.json ===")

if __name__ == "__main__":
    main()

